import {defineStore} from 'pinia';
import {login, getUserInfo} from '../../api/user/user.js';
import {setToken, getToken, removeToken} from '@/utils/auth.js';
import router from '@/router/index.js';

const ROLE_USER = 'user';
const ROLE_ADMIN = 'admin';

export const useUserStore = defineStore('user', {
    state: () => ({
        token: getToken() || '',
        userInfo: {},
    }),
    getters: {
        isLoggedIn: (state) => !!state.token,
        role: (state) => state.userInfo.role || '',
        name: (state) => state.userInfo.username || '',
    },
    actions: {
        // 用户登录
        async login(userInfo) {
            const {username, password} = userInfo;
            try {
                const response = await login({username: username.trim(), password: password});
                if (response.code === 200 && response.data.token) {
                    this.token = response.data.token;
                    setToken(this.token);
                    // 登录成功后获取用户信息
                    await this.getInfo();
                    return response;
                } else {
                    return Promise.reject(new Error(response.message || '登录失败'));
                }
            } catch (error) {
                return Promise.reject(error);
            }
        },

        // 获取用户信息
        async getInfo() {
            try {
                const response = await getUserInfo();
                if (response.code === 200 && response.data) {
                    this.userInfo = {
                        ...response.data,
                        role: response.data.role === 1 ? ROLE_USER : ROLE_ADMIN,
                    };
                    console.log(response);
                    return response.data;
                } else {
                    this.token = '';
                    this.userInfo = {};
                    removeToken();
                    return Promise.reject(new Error(response.message || '获取用户信息失败'));
                }
            } catch (error) {
                this.token = '';
                this.userInfo = {};
                removeToken();
                return Promise.reject(error);
            }
        },
        // 用户登出
        logout() {
            this.token = '';
            this.userInfo = {};
            router.push('/login').then(r => removeToken()); // 退出后跳转到登录页
        },

        // 重置 Token
        resetToken() {
            return new Promise((resolve) => {
                this.token = '';
                this.userInfo = {};
                removeToken();
                resolve();
            });
        },
    },
    // 开启持久化
    persist: true,
});